package service

import (
	"fmt"
	"ginweb/module/db"
	"ginweb/module/db/model"
	"time"
)

// FindUserByID 根据用户ID查找用户
func FindUserByID(id int) *model.SysUser {
	var user model.SysUser
	has, err := db.Ins.Where("id = ?", id).Get(&user)
	if err != nil {
		println(fmt.Printf("FindUserByID is error, ID: %d, ERROR: %s", id, err.Error()))
	} else {
		if has {
			return &user
		}
	}

	return nil
}

// FindAllUsers 查询所有用户
func FindAllUsers() *[]model.SysUser {
	var users []model.SysUser
	err := db.Ins.Find(&users)
	if err != nil {
		println(fmt.Printf("FindAllUsers is error, ERROR: %s", err.Error()))
		return nil
	}

	return &users
}

// DeleteUserByID 根据用户ID删除用户
func DeleteUserByID(id int) error {
	var user model.SysUser
	_, err := db.Ins.Where("id=?", id).Delete(&user)
	return err
}

// SaveUser 新增或修改用户
func SaveUser(u *model.SysUser) error {
	var err error
	now := time.Now()
	if u.ID > 0 {
		u.Updated = now
		_, err = db.Ins.Where("id=?", u.ID).Update(u)
	} else {
		u.Created = now
		u.Updated = now
		_, err = db.Ins.Insert(u)
	}

	if err != nil {
		println(fmt.Printf("SaveUser is error, ERROR: %s", err.Error()))
	}

	return err
}
